package com.yitiao.service;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
@AllArgsConstructor
public class ClientDiscoveryService {
    private final DiscoveryClient discoveryClient;

    @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 2000L, multiplier = 1.5))
    public List<ServiceInstance> getInstance(String serviceId) throws Exception {
        if (serviceId.equals("0")) {
            throw new RuntimeException("0");
        }
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
        instances.forEach(instance -> {
            log.info("instance host:[{}],instance port:[{}]", instance.getHost(), instance.getPort());
        });
        return instances;
    }

    @Recover
    public List<ServiceInstance> recover(Exception e) {
        log.info("--------获取失败，返回空");
        return new ArrayList<>();
    }
}
